package com.example.demo.controller;


import com.example.demo.commom.Result;
import com.example.demo.entity.LendRecord;
import com.example.demo.service.LendRecordService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/lendRecord")
public class LendRecordController {

    @Resource
    private LendRecordService lendRecordService;

    @DeleteMapping("/{isbn}")
    public Result<?> delete(@PathVariable String isbn) {
        int result = lendRecordService.deleteByIsbn(isbn);
        return result > 0 ? Result.success() : Result.error("400", "删除失败");
    }

    @PostMapping("/deleteRecord")
    public Result<?> deleteRecord(@RequestBody LendRecord lendRecord) {
        int result = lendRecordService.deleteByCondition(lendRecord);
        return result > 0 ? Result.success() : Result.error("400", "删除记录失败");
    }

    @PostMapping("/deleteRecords")
    public Result<?> deleteRecords(@RequestBody List<LendRecord> lendRecords) {
        int successCount = 0;
        for (LendRecord record : lendRecords) {
            int result = lendRecordService.deleteByCondition(record);
            if (result > 0) {
                successCount++;
            }
        }
        return successCount == lendRecords.size() ? Result.success() : Result.error("400", "部分删除失败");
    }

    @PostMapping
    public Result<?> save(@RequestBody LendRecord lendRecord) {
        int result = lendRecordService.insert(lendRecord);
        return result > 0 ? Result.success() : Result.error("400", "保存失败");
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search1,
                              @RequestParam(defaultValue = "") String search2,
                              @RequestParam(defaultValue = "") String search3) {
        List<LendRecord> records = lendRecordService.selectPage(pageNum, pageSize, search1, search2, search3);
        int total = lendRecordService.selectCount(search1, search2, search3);

        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        result.put("current", pageNum);
        result.put("size", pageSize);

        return Result.success(result);
    }

    @PutMapping("/{isbn}")
    public Result<?> update(@PathVariable String isbn, @RequestBody LendRecord lendRecord) {
        int result = lendRecordService.updateByIsbn(isbn, lendRecord);
        return result > 0 ? Result.success() : Result.error("400", "更新失败");
    }
}
